/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package GUI;

import Connection.SQLConnection;
import Entities.NHACUNGCAP;
import java.net.URL;
import java.sql.ResultSet;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javax.swing.JOptionPane;

/**
 * FXML Controller class
 *
 * @author lainh_000
 */
public class FX_NhaCungCapController implements Initializable {

    //khai báo control
    @FXML TextField txt_tenncc;
    @FXML TextField txt_diachi;
    @FXML TextField txt_sodt;
    @FXML Button btn_add;
    @FXML Button btn_edit;
    @FXML Button btn_del;
    @FXML Button btn_search;
    @FXML TableView table;
    @FXML TableColumn col_mancc;
    @FXML TableColumn col_tenncc;
    @FXML TableColumn col_diachi;
    @FXML TableColumn col_sodt;
    
    SQLConnection connect = new SQLConnection();
    ObservableList<NHACUNGCAP> data_ncc = FXCollections.observableArrayList();
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        KhoiTao();
        configureTextFieldOnlyNumber(txt_sodt);
        LoadData();
        configureTable();
    }    
    
    
    private void KhoiTao()
    {
        assert txt_tenncc != null;
        assert txt_diachi != null;
        assert txt_sodt != null;
        assert btn_add != null;
        assert btn_edit != null;
        assert btn_del != null;
        assert btn_search != null;
        assert col_mancc != null;
        assert col_tenncc != null;
        assert col_diachi != null;
        assert col_sodt != null;
        assert table != null;
    }
    
    //TextField chỉ cho nhập số
    private void configureTextFieldOnlyNumber(final TextField txt)
    {
        txt.lengthProperty().addListener(new ChangeListener<Number>(){
        @Override
         public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue)
         {              
            if(newValue.intValue() > oldValue.intValue())
            {
               char ch = txt.getText().charAt(oldValue.intValue());
               System.out.println("Length:"+ oldValue+"  "+ newValue +" "+ch);                   
               //Check if the new character is the number or other's
               if(!(ch >= '0' && ch <= '9' )){       
                    //if it's not number then just setText to previous one
                    txt.setText(txt.getText().substring(0,txt.getText().length()-1)); 
               }
            }
         }
        });
    }
    
    private void LoadData()
    {
        try {
            connect.getConnect();
            String query = "SELECT * FROM NHACUNGCAP";
            ResultSet rs = connect.executeQuery(query);
            int count = 0;
            while(rs.next())
            {
                NHACUNGCAP kh = new NHACUNGCAP(rs.getInt("mancc"),rs.getString("tenncc"),
                                    rs.getString("diachi"),rs.getString("sodt"));
                data_ncc.add(kh);
                count++;
            }
            connect.CloseConnect();
        } catch (Exception ex) {
             String stb="Không lấy được dữ liệu";
            JOptionPane.showMessageDialog(null,stb);
        }   
    }
    
    private void configureTable()
    {
        col_mancc.setCellValueFactory(new PropertyValueFactory<NHACUNGCAP, String>("mancc"));
        col_tenncc.setCellValueFactory(new PropertyValueFactory<NHACUNGCAP, String>("tenncc"));
        col_diachi.setCellValueFactory(new PropertyValueFactory<NHACUNGCAP, String>("diachi"));
        col_sodt.setCellValueFactory(new PropertyValueFactory<NHACUNGCAP, String>("sodt"));
        
        table.setItems(data_ncc);
        table.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        table.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() 
        { 
            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) 
            { 
                NHACUNGCAP ncc = (NHACUNGCAP)newValue;
                txt_tenncc.setText(ncc.getTenncc());
                txt_diachi.setText(ncc.getDiachi());
                txt_sodt.setText(ncc.getSodt());
            } 
        });
    }
    
    public void btn_addClick(ActionEvent event)
    {
        try {
            connect.getConnect();
            String ten = txt_tenncc.getText();
            String diachi = txt_diachi.getText();
            String sodt = txt_sodt.getText();
            String query = "INSERT INTO NHACUNGCAP (tenncc,diachi,sodt) "
                    + "VALUES('"+ten+"','"+diachi+"','"+sodt+"')";
            int rs = connect.executeUpdate(query);
            JOptionPane.showMessageDialog(null,"Thêm thành công");
            connect.CloseConnect();
        } catch (Exception ex) {
            String stb="Thêm dữ liệu không thành công.";
            JOptionPane.showMessageDialog(null,stb);       
        }
    }
    
    public void btn_editClick(ActionEvent event)
    {
         try {
            connect.getConnect();
            NHACUNGCAP ncc = (NHACUNGCAP)table.getSelectionModel().getSelectedItem();
            String tenncc = txt_tenncc.getText();
            String diachi = txt_diachi.getText();
            String sodt = txt_sodt.getText();
            String query = "UPDATE NHACUNGCAP "
                    + "SET tenncc = N'"+tenncc+"',diachi = N'"+diachi+"', sodt ='"+sodt+"' WHERE makh ="+ncc.getMancc()+";";
            int rs = connect.executeUpdate(query);
            JOptionPane.showMessageDialog(null,"Cập nhật thành công");
            connect.CloseConnect();
        } catch (Exception ex) {
            String stb="Cập nhập dữ liệu không thành công.";
            JOptionPane.showMessageDialog(null,stb);       
        }
    }
    
    public void btn_delClick(ActionEvent event)
    {
         try {
            connect.getConnect();
            NHACUNGCAP ncc = (NHACUNGCAP)table.getSelectionModel().getSelectedItem();
            String query = "DELETE FROM NHACUNGCAP WHERE mancc = "+ncc.getMancc()+";";
            int result = connect.executeUpdate(query);
            JOptionPane.showMessageDialog(null,"Xóa thành công");
            connect.CloseConnect();
        } catch (Exception ex) {
            String stb="Xóa dữ liệu không thành công.";
            JOptionPane.showMessageDialog(null,stb);       
        }
    }
    
    public void btn_searchClick(ActionEvent event)
    {
        
    }
    
}
